//
//  PopInteractiveAnimator.m
//  UIViewControllerTransitionDemo
//
//  Created by Guo Rui on 2017/7/4.
//  Copyright © 2017年 GR Harry. All rights reserved.
//

#import "PopInteractiveAnimator.h"
#import "SceneryDetailViewController.h"
#import "PushViewController.h"

@interface PopInteractiveAnimator ()
@property (weak, nonatomic) SceneryDetailViewController *viewController;
@property (assign, nonatomic) BOOL interactiving;
@property (weak, nonatomic) UIView *snapView;
@property (weak, nonatomic) id<UIViewControllerContextTransitioning> transitionContext;
@end

@implementation PopInteractiveAnimator

- (instancetype)initWithViewController:(SceneryDetailViewController *)viewController {
    if (self = [super init]) {
        self.viewController = viewController;
        
        UIPanGestureRecognizer *gestureRecognizer= [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
        [viewController.detailImageView addGestureRecognizer:gestureRecognizer];
    }
    return self;
}

- (void)pan:(UIPanGestureRecognizer *)recoginzer {
    
    CGPoint translation = [recoginzer translationInView:recoginzer.view];
    CGFloat distance = sqrt(translation.x * translation.x + translation.y * translation.y);
    
    CGFloat progress = distance / 300.f;
    progress = MIN(1.0, MAX(0.0, progress));
    
    switch (recoginzer.state) {
        case UIGestureRecognizerStateBegan:
        {
            self.interactiving = YES;
            [self.viewController.navigationController popViewControllerAnimated:YES];
        }
            break;
        case UIGestureRecognizerStateChanged:
        {
            self.snapView.transform = CGAffineTransformMakeTranslation(translation.x, translation.y);
            [self updateInteractiveTransition:progress];
        }
            break;
        case UIGestureRecognizerStateCancelled:
        {
            self.interactiving = NO;
            [self cancelInteractiveTransition];
        }
            break;
        case UIGestureRecognizerStateEnded:
        {
            self.interactiving = NO;
            if (progress > .5f) {
                [self finishInteractiveTransition];
            }
            else {
                [self cancelInteractiveTransition];
            }
        }
            break;
        default:
            break;
    }
}

- (void)startInteractiveTransition:(id<UIViewControllerContextTransitioning>)transitionContext {
    self.transitionContext = transitionContext;
    
    SceneryDetailViewController *fromVc = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    PushViewController *toVc = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    UIView *containerViwe = [transitionContext containerView];
    
    // 截图
    UIView *snapView = [fromVc.detailImageView snapshotViewAfterScreenUpdates:NO];
    snapView.frame = [containerViwe convertRect:fromVc.detailImageView.frame fromView:fromVc.detailImageView.superview];
    self.snapView = snapView;
    fromVc.detailImageView.hidden = YES;
    
    toVc.view.frame = [transitionContext finalFrameForViewController:toVc];
    UIImageView *cellImageViwe = [toVc cellForSelected].pictureImageView;
    cellImageViwe.hidden = YES;
    
    // 添加视图，注意顺序
    [containerViwe addSubview:snapView];
    [containerViwe insertSubview:toVc.view belowSubview:fromVc.view];
}

// 调用频率很高
- (void)updateInteractiveTransition:(CGFloat)percentComplete {
    [super updateInteractiveTransition:percentComplete];
    
    UIViewController *fromVc = [self.transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    fromVc.view.alpha = 1 - percentComplete;
}

- (void)cancelInteractiveTransition {
    [super cancelInteractiveTransition];
    
    SceneryDetailViewController *fromVc = [self.transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    PushViewController *toVc = [self.transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    
    __weak typeof(self) weakself = self;
    [UIView animateWithDuration:self.duration
                          delay:0
         usingSpringWithDamping:.8f
          initialSpringVelocity:.8f
                        options:UIViewAnimationOptionCurveLinear
                     animations:^{
                         weakself.snapView.transform = CGAffineTransformIdentity;
                         fromVc.view.alpha = 1.f;
                     } completion:^(BOOL finished) {
                         [weakself.snapView removeFromSuperview];
                         
                         fromVc.detailImageView.hidden = NO;
                         [toVc cellForSelected].pictureImageView.hidden = NO;
                         
                         [weakself.transitionContext completeTransition:NO];
                     }];
}

- (void)finishInteractiveTransition {
    [super finishInteractiveTransition];
    
    SceneryDetailViewController *fromVc = [self.transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    PushViewController *toVc = [self.transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    
    UIImageView *cellImageView = [toVc cellForSelected].pictureImageView;
    UIView *containerView = [self.transitionContext containerView];
    CGRect snapFinalRect = [containerView convertRect:cellImageView.frame fromView:cellImageView.superview];
    
    __weak typeof(self) weakself = self;
    [UIView animateWithDuration:self.duration
                          delay:0
         usingSpringWithDamping:.8f
          initialSpringVelocity:.8f
                        options:UIViewAnimationOptionCurveLinear
                     animations:^{
                         weakself.snapView.frame = snapFinalRect;
                         fromVc.view.alpha = 0.f;
                     } completion:^(BOOL finished) {
                         [weakself.snapView removeFromSuperview];
                         
                         cellImageView.hidden = NO;
                         [weakself.transitionContext completeTransition:YES];
                     }];
}

- (CGFloat)duration {
    return .4f;
}

@end
